<?php

/**
 * @Author: chenjianghui
 * @Date:   2018-08-07 13:49:20
 * @Last Modified by:   chenjianghui
 * @Last Modified time: 2018-08-10 15:42:29
 */
namespace app\app\controller;

use app\common\lib\User as Lib_user;
use app\common\model\User as UserModel;
use app\common\model\VerifyCode;

class User extends Common
{
    /**
     * 手机号注册
     * @Author   chenjianghui
     * @DateTime 2018-08-07T13:50:34+0800
     * @return   [type]                   [description]
     */
    public function register()
    {
        $data     = input('post.');
        $validate = validate('User');
        if (!$validate->check($data)) {
            renderJson($validate->getError(), 0);
        }
        if ($data['password'] != $data['password_again']) {
            renderJson('两个输入密码不一致，请重新设置', 0);
        }
        // 用户唯一性判断
        $model_user = UserModel::where('mobile', $data['mobile'])->find();
        if ($model_user) {
            renderJson('该手机号码已被注册', 0);
        }
        // 工种校验
        $work_sort_info = model('WorkSort')->where('sort_id', $data['sort_id'])->find();
        if (!$work_sort_info){
            renderJson('您的工种选择有误', 0);
        }
        // 验证码校验
        $code_obj         = VerifyCode::checkCode('register_mobile', $data['mobile'], $data['code']);
        $data['username'] = $data['mobile'];
        // 新建user数据
        $user_obj = new UserModel($data);
        $uid      = $user_obj->smsRegister();
        if ($uid) {
            $code_obj->toSuccess(array('uid' => $uid));
            // // 注册完直接登录
            // $access_token = Lib_user::encode_token(array('uid' => $uid));
            // UserModel::where('uid', $uid)->update(['access_token' => $access_token, 'last_login_time' => time(), 'last_login_ip' => request()->ip()]);
            // renderJson('注册成功', 1, array(
            //     'access_token' => $access_token,
            //     'user_id'      => $uid,
            // ));
            renderJson('注册成功', 1);
        } else {
            renderJson('注册失败', 0);
        }
    }

    /**
     * 手机号快速登录
     * @Author   chenjianghui
     * @DateTime 2018-08-07T14:16:09+0800
     * @return   [type]                   [description]
     */
    public function loginByMobile()
    {
        $data = input('post.');
        $rule = [
            'mobile' => 'require|/^1[3456789]\d{9}$/',
            'code'   => 'require',
        ];
        $msg = [
            'mobile.require' => '请输入手机号码',
            'mobile'         => '您输入的手机号码格式不正确，请重新输入',
            'code.require'   => '请输入短信验证码',
        ];
        $validate = new \think\Validate($rule, $msg);
        if (!$validate->check($data)) {
            renderJson($validate->getError(), 0);
        }
        // 验证码校验
        $code_obj = VerifyCode::checkCode('login_mobile', $data['mobile'], $data['code']);
        // 判断用户是否存在
        $user_obj = UserModel::where('mobile', $data['mobile'])->find();
        if (!$user_obj) {
            renderJson('您输入的帐号不存在，请重新输入', 0);
        }
        // 登录
        $access_token = $user_obj->loginByMobile();
        if ($access_token) {
            $code_obj->toSuccess(array('uid' => $user_obj->uid)); // 验证码状态修改
            renderJson('登录成功', 1, array(
                'access_token' => $access_token,
                'user_id'      => $user_obj->uid,
            ));
        }
        renderJson('用户名或密码错误', 0);
    }

    /**
     * 账号密码登录
     * @Author   chenjianghui
     * @DateTime 2018-08-07T14:41:56+0800
     * @return   [type]                   [description]
     */
    public function loginByAccount()
    {
        $data = input('post.');
        $rule = [
            'account'  => 'require',
            'password' => 'require',
        ];
        $msg = [
            'account.require'  => '账号不能为空',
            'password.require' => '请输入登录密码',
        ];
        $str = "%**#" . $data['account'];
        if (strpos($str, '@')) {
            if (!check_email($data['account'])) {
                renderJson('邮箱账号格式不正确', 0);
            }
        } else {
            if (!check_mobile($data['account'])) {
                renderJson('手机格式不正确', 0);
            }
        }
        $validate = new \think\Validate($rule, $msg);
        if (!$validate->check($data)) {
            renderJson($validate->getError(), 0);
        }
        // 判断用户是否存在
        $user_obj = UserModel::where('mobile|email', $data['account'])->find();
        if (!$user_obj) {
            renderJson('您输入的帐号不存在，请重新输入', 0);
        }
        // 密码校验
        $access_token = $user_obj->login($data);

        if ($access_token) {
            renderJson('登录成功', 1, array(
                'access_token' => $access_token,
                'user_id'      => $user_obj->uid,
            ));
        }
        renderJson('用户名或密码错误', 0);
    }

    /**
     * 找回登录密码
     * @Author   chenjianghui
     * @DateTime 2018-08-07T14:47:52+0800
     * @return   [type]                   [description]
     */
    public function forgetLoginPassword()
    {
        $data = input('post.');
        $rule = [
            'mobile'         => 'require|/^1[3456789]\d{9}$/',
            'code'           => 'require',
            'password'       => 'require|min:6|max:12|/^[0-9a-zA-Z_]{1,}$/',
            'password_again' => 'require',
        ];
        $msg = [
            'mobile.require'         => '请输入手机号码',
            'mobile'                 => '您输入的手机号码格式不正确，请重新输入',
            'code.require'           => '请输入短信验证码',
            'password.require'       => '请输入密码',
            'password.min'           => '密码长度为6-12字符',
            'password.max'           => '密码长度为6-12字符',
            'password'               => '密码不可包含非法字符',
            'password_again.require' => '请输入重复密码',
        ];
        $validate = new \think\Validate($rule, $msg);
        if (!$validate->check($data)) {
            renderJson($validate->getError(), 0);
        }
        if ($data['password'] != $data['password_again']) {
            renderJson('两个输入密码不一致，请重新设置', 0);
        }
        // 验证码校验
        $code_obj = VerifyCode::checkCode('find_password_mobile', $data['mobile'], $data['code']);
        // 判断用户是否存在
        $user_obj = UserModel::where('mobile', $data['mobile'])->find();
        if (!$user_obj) {
            renderJson('您输入的帐号不存在，请重新输入', 0);
        }
        try {
            $res = $user_obj->changePassword($data['password']);
            if ($res) {
                $code_obj->toSuccess(array('uid' => $user_obj->uid)); // 验证码状态修改
            }
        } catch (\Exception $e) {
            renderJson('修改密码失败', 0);
        }
        renderJson('修改密码成功', 1);
    }

    /**
     * 退出
     * @Author   chenjianghui
     * @DateTime 2018-08-07T16:27:30+0800
     * @return   [type]                   [description]
     */
    public function logout()
    {
        Lib_user::check_login();
        $userObj = UserModel::where('uid', $this->uid)->find();
        if ($userObj && $userObj->logout()) {
            renderJson('用户已注销', 1);
        }
        renderJson('未知错误', 0);
    }

    /**
     * 修改登录密码
     * @Author   chenjianghui
     * @DateTime 2018-08-07T16:37:27+0800
     * @return   [type]                   [description]
     */
    public function changePassword()
    {
        Lib_user::check_login();
        $data = input('post.');
        $rule = [
            'old_password'       => 'require',
            'new_password'       => 'require|min:6|max:12|/^[0-9a-zA-Z_]{1,}$/',
            'new_password_again' => 'require',
        ];
        $msg = [
            'old_password.require'       => '请输入原密码',
            'new_password.require'       => '请输入新密码',
            'new_password.min'           => '新密码长度为6-12字符',
            'new_password.max'           => '新密码长度为6-12字符',
            'new_password'               => '密码不可包含非法字符',
            'new_password_again.require' => '请再次输入密码',
        ];
        $validate = new \think\Validate($rule, $msg);
        if (!$validate->check($data)) {
            renderJson($validate->getError(), 0);
        }
        $old_password        = $data['old_password'];
        $new_password        = $data['new_password'];
        $new_password_repeat = $data['new_password_again'];
        if ($new_password != $new_password_repeat) {
            renderJson('两个输入密码不一致，请重新设置', 0);
        }
        // 获取用户对象
        $userObj = UserModel::where('uid', $this->uid)->find();
        if (!$userObj) {
            renderJson('账户存在异常', 0);
        }
        if (!$userObj->verifyPassword($old_password)) {
            renderJson('原密码不正确', 0);
        }
        // 修改密码
        try {
            $userObj->changePassword($new_password);
        } catch (\Exception $e) {
            renderJson('修改密码失败', 0);
        }
        renderJson('修改密码成功', 1);
    }

    /**
     * 手机号更换绑定
     * @Author   chenjianghui
     * @DateTime 2018-08-07T17:20:13+0800
     * @return   [type]                   [description]
     */
    public function changeMobile()
    {
        Lib_user::check_login();
        $data = input('post.');
        $rule = [
            'mobile' => 'require|/^1[3456789]\d{9}$/',
            'code'   => 'require',
        ];
        $msg = [
            'mobile.require' => '请输入手机号码',
            'mobile'         => '您输入的手机号码格式不正确，请重新输入',
            'code.require'   => '请输入短信验证码',
        ];
        $validate = new \think\Validate($rule, $msg);
        if (!$validate->check($data)) {
            renderJson($validate->getError(), 0);
        }
        $has_mobile = UserModel::where('mobile', $data['mobile'])->where('uid', '<>', $this->uid)->find();
        if ($has_mobile) {
            renderJson('该手机号已被绑定，请重新输入', 0);
        }
        // 验证码校验
        $code_obj = VerifyCode::checkCode('change_mobile', $data['mobile'], $data['code']);
        // 判断用户是否存在
        $user_obj = UserModel::where('uid', $this->uid)->find();
        if ($user_obj && $user_obj->mobile && $user_obj->mobile == $data['mobile']) {
            renderJson('新旧手机号码不能相同', 0);
        } else {
            $res = $user_obj->save(['mobile' => $data['mobile']]);
            if ($res) {
                $code_obj->toSuccess(['uid' => $this->uid]);
                renderJson('更换成功', 1);
            } else {
                renderJson('更换失败', 0);
            }
        }
    }

    /**
     * 获取用户信息
     * @Author   chenjianghui
     * @DateTime 2018-08-07T18:38:57+0800
     * @return   [type]                   [description]
     */
    public function getUserInfo()
    {
        Lib_user::check_login();
        $user_info = (new UserModel())->getUserInfoById($this->uid);
        $info      = [
            'mobile'   => $user_info->mobile ?: '',
            'email'    => $user_info->email ?: '',
            'username' => $user_info->username ?: '',
        ];
        // 头像
        if ($user_info->avatar && !preg_match('/(http:\/\/)|(https:\/\/)/i', $user_info->avatar)) {
            $info['avatar'] = 'http://' . $_SERVER['HTTP_HOST'] . $user_info->avatar;
        } else if ($user_info->avatar && preg_match('/(http:\/\/)|(https:\/\/)/i', $user_info->avatar)) {
            $info['avatar'] = $user_info->avatar;
        } else {
            $info['avatar'] = 'http://' . $_SERVER['HTTP_HOST'] . '/static/images/head_img.png';
        }
        // 工种
        $info['sort_id'] = $user_info->sort_id ? : 0;
        $info['sort_name'] = '';
        if ($user_info->sort_id){
            $work_sort_info = model('WorkSort')->where('sort_id', $user_info->sort_id)->find();
            $info['sort_name'] = $work_sort_info['sort_name'] ? : '';
        }
        // 实名认证状态
        $realname_info = model('AuthRealname')->where('uid', $this->uid)->find();
        if ($realname_info){
            $info['realname_status'] = $realname_info['auth_stauts'];
        } else{
            $info['realname_status'] = '-1';//未进行实名认证
        }
        renderJson('个人信息', 1, $info);
    }

    /**
     * 昵称获取
     * @Author   chenjianghui
     * @DateTime 2018-08-08T09:08:30+0800
     * @return   [type]                   [description]
     */
    public function getUserName()
    {
        Lib_user::check_login();
        $username = (new UserModel)->getNameById($this->uid);
        renderJson('用户名', 1, ['username' => $username]);
    }

    /**
     * 头像获取
     * @Author   chenjianghui
     * @DateTime 2018-08-08T09:08:30+0800
     * @return   [type]                   [description]
     */
    public function getAvatar()
    {
        Lib_user::check_login();
        $avatar = (new UserModel)->getAvatarById($this->uid);
        renderJson('头像', 1, ['avatar' => $avatar]);
    }

    /**
     * 更新用户信息
     * @Author   chenjianghui
     * @DateTime 2018-08-07T19:20:34+0800
     * @return   [type]                   [description]
     */
    public function updateInfo()
    {
        Lib_user::check_login();
        $data = input('post.');
        $rule = [
            'username' => "unique:User,username,$this->uid",
        ];
        $msg = [
            'username.unique' => '用户名已存在',
        ];
        $validate = new \think\Validate($rule, $msg);
        if (!$validate->check($data)) {
            renderJson($validate->getError(), 0);
        }
        // 获取用户信息
        $user_obj = UserModel::where('uid', $this->uid)->find();
        if (!$user_obj) {
            renderJson('帐号存在异常', 0);
        }
        // 修改用户个人信息
        $data['uid'] = $this->uid;
        if (request()->file('avatar')) {
            $data['avatar'] = \app\common\lib\Upload::uploadByFile('avatar', 'avatar');
        }
        try {
            $user_obj->updateUserInfo($data);
        } catch (\Exception $e) {
            renderJson('保存失败', 0);
        }
        renderJson('保存成功', 1);
    }

    /**
     * 邮箱绑定
     * @Author   chenjianghui
     * @DateTime 2018-08-08T16:35:49+0800
     * @return   [type]                   [description]
     */
    public function bindEmail()
    {
        Lib_user::check_login();
        $data = input('post.');
        if (empty($data['code'])) {
            renderJson('验证码不能为空', 0);
        }
        if (empty($data['email'])) {
            renderJson('邮箱帐号不能为空', 0);
        }
        if (!check_email($data['email'])) {
            renderJson('邮箱格式不正确', 0);
        }
        // 验证码校验
        $code_obj = VerifyCode::checkCode('bind_email', $data['email'], $data['code']);
        $rule     = [
            'email' => "unique:User,email,$this->uid",
        ];
        $msg = [
            'email.unique' => '邮箱已存在',
        ];
        $validate = new \think\Validate($rule, $msg);
        if (!$validate->check($data)) {
            renderJson($validate->getError(), 0);
        }
        $res = UserModel::where('uid', $this->uid)->update(['email' => $data['email']]);
        if ($res) {
            renderJson('邮箱绑定成功', 1);
        }
        renderJson('绑定失败', 0);
    }

    /**
     * 验证手机号是否唯一
     * @Author   chenjianghui
     * @DateTime 2018-08-08T16:51:26+0800
     * @return   [type]                   [description]
     */
    public function checkMobile()
    {
        Lib_user::check_login();
        $data = input('post.');
        if (empty($data['mobile'])) {
            renderJson('手机号不能为空', 0);
        }
        if (!check_mobile($data['mobile'])) {
            renderJson('手机号格式不正确', 0);
        }
        $user = UserModel::where('mobile', $data['mobile'])->find();
        if ($user) {
            renderJson('该手机号已存在', 1);
        }
        renderJson('该手机号可以使用', 2);
    }

    /**
     * 意见反馈
     * @Author   chenjianghui
     * @DateTime 2018-08-07T17:00:01+0800
     * @return   [type]                   [description]
     */
    public function feedBack()
    {
        Lib_user::check_login();
        $data = input('post.');
        if (empty($data['type'])) {
            renderJson('请填写反馈类型', 0);
        }
        if (empty($data['content'])) {
            renderJson('请填写反馈内容', 0);
        }
        if (mb_strlen($data['content'], 'utf-8') > 150) {
            renderJson('反馈内容不能超过150字', 0);
        }
        $arr = [
            'uid'           => $this->uid,
            'content'       => $data['content'],
            'on_time'       => time(),
            'deal_status'   => 0,
            'feedBack_type' => $data['type'],
        ];
        $res = \app\common\model\FeedBack::create($arr);
        if ($res) {
            renderJson('反馈成功', 1);
        } else {
            renderJson('反馈失败', 0);
        }
    }
}
